<template>
  <div id="product">
    <div class="product_top">
      <el-button type="primary" @click="addproduct">添加</el-button>
      <el-input v-model="input" placeholder="请输入产品名称" clearable />
      <el-button type="primary" @click="search">搜索</el-button>
    </div>
    <div class="product_center">
      <el-table
        :data="productList"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="编号"
          width="180"
          align="center"
        />
        <el-table-column
          prop="name"
          label="产品名称"
          width="180"
          align="center"
        />
        <el-table-column
          prop="price"
          label="价格"
          width="180"
          align="center"
        />
        <el-table-column
          prop="description"
          label="产品描述"
          align="center"
        />
        <el-table-column
          prop="categoryName"
          label="所属产品"
          width="180"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="deletepro(scope.row,scope.$index)">删除</el-button>
            <el-button type="text" @click="editorpro(scope.row)">编辑</el-button>
            <el-button type="text" @click="details(scope.row.id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="product_buttom">
      <div class="block">
        <el-pagination
          :current-page.sync="currentPage1"
          :page-size="5"
          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/删除的模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" top="8vh">
      <el-form ref="proForm" :model="form" :rules="rules">
        <el-form-item label="产品名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="form.price" autocomplete="off" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="所属栏目" :label-width="formLabelWidth" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择所属栏目">
            <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="handleChange"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('proForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'querystring'

export default {
  data() {
    return {
      input: '',
      total: 0,
      currentPage1: 1,
      pageSize: 5,
      products: [],
      categorys: [],
      // 模态框
      title: '添加产品信息',
      dialogFormVisible: false,
      form: {
        name: '',
        price: '',
        delivery: false,
        categoryId: '',
        description: ''
      },
      formLabelWidth: '120px',
      textarea: '',
      fileList: [{
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }],
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入产品价格', trigger: 'blur' },
          { min: 2, max: 0x3f3f3f3f, message: '长度大于0的字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    productList() {
      var self = this
      // this.products--所有产品
      // console.log(this.products,'产品');
      // 查询所有category
      // console.log(this.categorys,'栏目');
      // 每一个产品id匹配所有category,匹配成功后将当前category的name->当前产品
      this.products.forEach((item) => {
        // item->每一个产品对象
        for (var i = 0; i < self.categorys.length; i++) {
          // categorys[i]:每一个栏目对象
          if (item.categoryId == self.categorys[i].id) {
            item.categoryName = self.categorys[i].name
          // console.log(item,'123131');
          }
        }
      })
      return this.products
    }
  },
  created() {
    this.findAllCategory().then(response => {
      // 1,将所有栏目信息共享
      this.categorys = response.data.data
      // console.log(this.categorys,'栏目');
      // 2，请求所有产品信息
      this.findAllPro()
    })
  },
  methods: {
    // 给添加/删除的确定按钮绑定事件
    submitForm(formName) {
      var self = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          self.$axios.post('/product/saveOrUpdate', qs.stringify(self.form)).then(response => {
            if (response.data.status == 200) {
              // 保存成功
              // 1，关闭模态框
              // 2，刷新页面
              self.findAllPro()
              // 3,提示用户保存成功-弹框
              this.$message({
                message: '保存成功',
                type: 'success'
              })
            } else {
              // 保存失败
              this.$message.error('保存失败')
            }
            self.dialogFormVisible = false
          })
        } else {
          // 表单验证失败
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(proForm) {
      this.$refs[proForm].resetFields()
    },

    // 给详情按钮绑定事件
    details(id) {
      this.$router.push({ path: '/detailsOne/index', query: { id: id }})
    },

    // 给编辑按钮添加事件
    editorpro(row) {
      this.dialogFormVisible = true
      this.title = '修改产品信息'
      this.form = {
        id: row.id,
        name: row.name,
        price: row.price,
        categoryId: row.categoryId,
        description: row.description
      }
    },

    // 给删除按钮绑定事件
    deletepro(row, index) {
      var self = this
      var id = row.id

      // 触发弹出确定删除对话框
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认删除
        // 发送删除请求
        this.$axios.get('/product/deleteById', { params: { id }}).then(response => {
          if (response.data.status == 200) {
            // 删除成功-刷新页面-弹框
            self.findAllPro()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            //  删除失败
            this.$message.error('删除失败')
          }
        })
        // 取消删除
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 给添加按钮绑定事件
    addproduct() {
      this.dialogFormVisible = true
      this.title = '添加产品信息'
      this.form = {}
    },

    // 给搜索按钮添加绑定事件
    search() {
      // 1,获取用户输入的内容
      if (this.input) {
        // 2,发送请求->给表格展示
        this.findAllPro(this.input)
      } else {
        this.findAllPro()
      }
    },

    // 封装请求所有栏目的函数
    findAllCategory() {
      return this.$axios.get('/category/findAll')
    },
    // 封装分页获取全部产品信息
    findAllPro(name) {
      if (name) {
        // 搜索调用
        var data = {
          page: this.currentPage1,
          pageSize: this.pageSize,
          name: name
        }
      } else {
        // 不搜索时调用
        var data = {
          page: this.currentPage1,
          pageSize: this.pageSize
        }
      }

      this.$axios.post('/product/queryProductCascadeCategory', qs.stringify(data)).then(response => {
        console.log(response.data.data)
        this.products = response.data.data.list
        this.total = response.data.data.total
      })
    },

    // 分页管理
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage1 = val
      this.findAllPro()
    },

    // 文件上传
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3)
    }
  }
}
</script>
<style lang="scss" scoped>
#product{
  padding: 20px;
  .product_top .el-input{
    width: 25%;
    margin-left:20px;
  }
}
.product_top :nth-child(3){
  margin-left: 15px;
}
</style>
